package heman.server.controllers;

import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import heman.server.entities.Table;
import heman.server.entities.TableManager;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

/**
 * RejectResponseController handles REJECTRESPONSE message
 * We hack this message for rejecting invitation.
 * 
 * <xs:element name="rejectResponse">
 * 	<xs:complexType>
 * 		<xs:attribute name="table" type="table-id" use="required" /> 
 * 		<xs:attribute name="player" type="valid-player-id" use="required" /> 
 * 	</xs:complexType>
 * </xs:element>
 *
 * @author Yanyi Zhang
 *
 */

public class RejectResponseController implements IProcessServerMessage {
	public boolean process(Communicator com, Message m){
		String originator = m.getOriginator();
		NamedNodeMap map = m.contents().getAttributes();
		String tableID=map.
        		getNamedItem("table").getNodeValue();
		Table TargetTable=TableManager.getInstance().getTable(tableID);
		Player TargetPlayer=PlayerManager.getInstance().getPlayer(originator);
		if(!TargetTable.removeinvitePlayer(TargetPlayer))
			return false;
		Message r;
		StringBuilder sb = new StringBuilder(Message.responseHeader(true,m.id));
		sb.append("<rejectResponse table=\"");
		sb.append(tableID);
		sb.append("\" player=\"");
		sb.append(originator);
		sb.append("\"/></response>");
		Document d = Message.construct(sb.toString());
        r = new Message (d);
        r.setOriginator(originator);
        r.setRecipient(TargetTable.getModerator().getId());//respond to Moderator
        return com.distribute(r);
	}
}
